package com.heima.wemedia.service.impl;

import com.aliyun.oss.internal.ResponseParsers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JsonUtils;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.dtos.WmNewsResultDTO;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.entity.WmNews;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewAutidService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.xml.bind.v2.model.core.ID;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.math.Primes;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-10-19
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialService materialService;

    @Autowired
    private WmMaterialService wmMaterialService;

    @Autowired
    private WmNewAutidService autidService;

    @Override

    public void submit(WmNewsDto dto) {
        Integer userId = UserThreadLocalUtils.getUserId();
        WmNews wmNews = BeanHelper.copyProperties(dto, WmNews.class);
        Integer id = dto.getId();
        if (id == null) {
            wmNews.setWmUserId(userId);
            wmNews.setCreatedTime(new Date());
        }
        if (CollectionUtils.isEmpty(dto.getImages())) {
            String imagesStr = dto.getImages().stream().collect(Collectors.joining(","));
            wmNews.setImages(imagesStr);
        }
        if (dto.getStatus() == 1) {
            wmNews.setSubmitedTime(new Date());
        }
        boolean b = saveOrUpdate(wmNews);
        if (b != true) {
            log.error("报错修该翁庄失败");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        Integer id1 = wmNews.getId();
        if (dto.getId() != null) {
            materialService.DeleteById(id1);
        }
        List<Integer> getcontentids = getcontent(dto.getContent());
        materialService.saveaa(getcontentids, id1, 0);
        if (CollectionUtils.isEmpty(dto.getImages())) {
            List<Integer> getimagesids = getImages(dto.getImages());
            materialService.saveaa(getcontentids, id1, 0);
        }

autidService.auditWmNew(wmNews);
//        ExecutorService threadPool = Executors.newCachedThreadPool();
//        threadPool.submit(new Runnable() {
//            @Override
//            public void run() {
//                autidService.auditWmNew(wmNews);
//            }
//        });


    }

    private List<Integer> getImages(List<String> images) {
        LambdaQueryWrapper<WmMaterial> lqw = new LambdaQueryWrapper<>();
        lqw.in(WmMaterial::getUrl, images);
        List<WmMaterial> list = wmMaterialService.list(lqw);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<Integer> collect = list.stream().map(WmMaterial::getId).collect(Collectors.toList());
        return collect;
    }


    private List<Integer> getcontent(String content) {

        if (StringUtils.isBlank(content)) {
            return null;
        }
        List<Integer> mt = new ArrayList<>();
        List<Map<String, Object>> list = JsonUtils.nativeRead(content, new TypeReference<List<Map<String, Object>>>() {
        });

        for (Map<String, Object> map : list) {
            String type = map.get("type").toString();
            if ("image".equals(type)) {
                Integer ma = Integer.valueOf(map.get("id").toString());
                mt.add(ma);
            }
        }
        return mt;
    }

    @Override
    public WmNewsPageReqDto getOneWmNews(Integer id) {
//        Integer userId = UserThreadLocalUtils.getUserId();
//        if (userId == null || userId == 0) {
//            log.error("用户没有登录");
//            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
//        }
        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(WmNews::getWmUserId, userId);
        lqw.eq(WmNews::getId, id);
        WmNews wmNews = getOne(lqw);
        if (wmNews == null) {
            log.error("文章不存在");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        return BeanHelper.copyProperties(wmNews, WmNewsPageReqDto.class);
    }

    @Override
    public ResponseResult<WmNewsResultDTO> findByPage(WmNewsPageReqDto dto) {
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId == null || userId == 0) {
            log.error("用户没有登录");
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        Page<WmNews> iPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
        Integer status = dto.getStatus();
        if (status != null && status != -1) {
            if (status == 1) {
                lqw.in(WmNews::getStatus, 1, 3);
            } else if (status == 4) {
                lqw.in(WmNews::getStatus, 4, 8, 9);
            } else {
                lqw.in(WmNews::getStatus, dto.getStatus());
            }
        }
        lqw.eq(WmNews::getWmUserId, userId)
                .eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId())
                .like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword())
                .gt(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate())
                .lt(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate());
        Page<WmNews> page = page(iPage, lqw);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            log.error("结果集为空");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return new PageResult<>(dto.getPage(), dto.getSize(), page.getTotal(),
                BeanHelper.copyWithCollection(page.getRecords(), WmNewsPageReqDto.class));
    }
}
